﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Domain.Service;
using Domain.Entities;
using Domain.Service.ObjectCache;
using Domain.Service.System;
using Infrastructure.System;
using Presentation.Core;
using System.Transactions;
using Infrastructure.Order;

namespace DDD从零起步.Controllers
{
    public class HomeController : BaseController
    {
        /// <summary>
        /// 延时初始化
        /// </summary>
        Lazy<UserService> userService;
        IUserRepository iUserRepository;
        public HomeController()
        {
            iUserRepository = new UserRepository();
            userService = new Lazy<UserService>(() => { return new UserService(iUserRepository); });
        }
        /// <summary>
        /// 用户列表
        /// 领域规约：UserListSpecification
        /// 领域服务：UserService
        /// </summary>
        /// <param name="fromDate"></param>
        /// <param name="toDate"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public ActionResult Index(DateTime? fromDate, DateTime? toDate, int? status)
        {
            UserListSpecification dateSpecification = new UserListSpecification(fromDate, toDate, status);
            var model = userService.Value.GetWebManageUsers(dateSpecification);
            return View(model);
        }

        public ContentResult CreateOrder()
        {
            #region 对象初始化
            Domain.Core.IUnitOfWork _iUnitWork = new backgroundEntities();
            Order_Info entity = new Order_Info
            {
                CreateDate = DateTime.Now,
                UserID = 1,
                Order_Detail = new List<Order_Detail>
                {
                    new Order_Detail
                    {
                      ProductID=14,
                      ProductName="香蕉1" 
                    },
                     new Order_Detail 
                    {
                      ProductID=15,
                      ProductName="香蕉2"
                    }
                }
            };
            #endregion
            int p1 = new ProductRepository(_iUnitWork).GetEntities()
                .FirstOrDefault(i => i.ProductID == 14)
                .SaleCount;
            int p2 = new ProductRepository(_iUnitWork).GetEntities()
                .FirstOrDefault(i => i.ProductID == 15)
                .SaleCount;

            //int p1 = new ProductRepository(_iUnitWork).Find(14).SaleCount ?? 0;
            //int p2 = new ProductRepository(_iUnitWork).Find(15).SaleCount ?? 0;

            #region 操作单元的使用
            using (TransactionScope trans = new TransactionScope())
            {
                try
                {

                    _iUnitWork.IsNotSubmit = true;//保存repository类不会去提交
                    new OrderRepository(_iUnitWork).InsertOrder(entity);
                    new ProductRepository(_iUnitWork).Modify(i => new Product
                    {
                        ProductID = 14,
                        SaleCount = p1 + 1
                    });
                    new ProductRepository(_iUnitWork).Modify(i => new Product
                    {
                        ProductID = 15,
                        SaleCount = p2 + 1
                    });
                    _iUnitWork.Save();
                    trans.Complete();
                    return Content("插入订单成功");
                }
                catch (Exception ex)
                {

                    return Content(ex.Message);
                }

            }
            #endregion

        }
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(WebManageUsers entity)
        {
            entity.CreateDate = DateTime.Now;
            entity.UpdateDate = DateTime.Now;
            entity.Status = 100;
            if (ModelState.IsValid)
            {
                using (TransactionScope trans = new TransactionScope())
                {
                    try
                    {
                        iUserRepository.Add(entity);
                        return RedirectToAction("Index");
                    }
                    catch (TransactionAbortedException)
                    {

                        throw;
                    }
                }

            }
            return View();
        }

        public ActionResult Edit(int id)
        {
            var model = iUserRepository.Find(id);
            return View(model);
        }

        //
        // POST: /Department/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                WebManageUsers entity = iUserRepository.Find(id);//取当前实体
                TryUpdateModel(entity);//从视频更新到模型
                entity.UpdateDate = DateTime.Now;//手动为模型赋值
                iUserRepository.Modify(entity);//提交到数据库
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Delete(int id)
        {
            try
            {
                iUserRepository.Remove(new WebManageUsers { ManageUserID = id });
                return RedirectArtDialogToAction("操作成功", "Index");
            }
            catch (Exception ex)
            {

                return RedirectArtDialogToAction("操作失败，信息为:" + ex.Message, "Index");
            }
        }

        public ActionResult FileUpLoad()
        {
            return View();
        }
    }
}
